import re
from threading import Thread
from datetime import datetime, timedelta
from tools.autoregister.autoregister import telnetip


def delInvalidOnt():
    client = telnetip('124.95.249.231', 23, 'huawei', 'Bandx&19')
    client.login_host()
    client.base_config(1)
    board_info = client.board_info(scope="usable")
    board_list = [board[0] for board in board_info[0]]

    for board in board_list:
        port_list = client.board_one(board, scope="port_num")
        for port in port_list:
            command = " display ont info 0 %s %s all" % (board, port)
            ont_info = client.commandResult_fun(command)
            result = [i for i in ont_info.splitlines()[5:] if '离线' in i]
            for i in result:
                frameid, slotid, board_port, ontid = re.findall("\d+", i)[:4]
                deleteOne(client, frameid, slotid, board_port, ontid)


def deleteOne(client, frameid, slotid, board_port, ontid):
    command = 'display service-port port {}/{}/{} ont {}\n'.format(frameid, slotid, board_port.strip(), ontid)
    result = client.commandResult_fun(command)
    if "面向交换业务流列表" in result:
        if "common" in result:
            ont_type = [i for i in result.split("common")[1].split("\n")[0].split(" ") if i != ''][0]
        else:
            ont_type = [i for i in result.split("stacking")[1].split("\n")[0].split(" ") if i != ''][0]
        delServerPort = re.findall(" *([0-9].*?)[ge]pon ", result)[0].split(" ")[0]
        client.commandResult_fun("undo service-port %s" % delServerPort)
        interface_command = "interface {} {}/{}".format(ont_type, frameid, slotid)
        client.commandResult_fun(command=interface_command)
        ontdel_command = 'ont delete {} {}'.format(board_port.strip(), ontid)
        client.commandResult_fun(command=ontdel_command)
        client.commandResult_fun(command="quit")


if __name__ == '__main__':
    delInvalidOnt()
